<template>
  <div ref="containerRef" :id="id">
    <slot></slot>
    <Teleport to="body">
      <Transition
        @beforeEnter="handleBeforeEnter"
        @enter="handleEnter"
        @afterEnter="handleAfterEnter"
      >
        <div
          v-if="showMenu"
          class="context-menu"
          :style="{ left: menuX + 'px', top: menuY + 'px' }"
        >
          <div class="menu-list">
            <!-- 添加菜单的点击事件 -->
            <div
              @click="handleClick(item)"
              class="menu-item"
              v-for="item in menu"
              :key="item.label"
            >
              <el-icon>
                <component :is="item.icon?.split('el-icon-')[1]"></component>
              </el-icon>
              <span>{{ item.label }}</span>
            </div>
          </div>
        </div>
      </Transition>
    </Teleport>
  </div>
</template>

<script setup lang="ts">
// 模块引入
import { useTemplateRef, useId } from 'vue'
import { useContextMenu } from './useContextMenu'

defineOptions({
  // 组件名称
  name: 'ContextMenuComp',
  // 继承透传，是否继承没在子组件声明的父组件的属性
  inheritAttrs: true
})

interface IMenu {
  icon?: string
  label: string
  value: string
}
interface IProps {
  menu: IMenu[]
}

defineProps<IProps>()

const id = useId()
// console.log(id)

const containerRef = useTemplateRef<HTMLDivElement>('containerRef')
const { showMenu, menuX, menuY } = useContextMenu(containerRef)
const emit = defineEmits(['selectHandle'])

const handleClick = (item: IMenu) => {
  showMenu.value = false
  emit('selectHandle', item)
}

const handleBeforeEnter = (el: Element) => {
  if (el instanceof HTMLElement) {
    el.style.height = '0'
  }
}
const handleAfterEnter = (el: Element) => {
  if (el instanceof HTMLElement) {
    el.style.height = 'none'
  }
}
const handleEnter = (el: Element) => {
  if (el instanceof HTMLElement) {
    el.style.height = 'auto'
    const height = el.clientHeight
    el.style.height = '0'
    requestAnimationFrame(() => {
      el.style.height = height + 'px'
      el.style.transition = '0.5s'
    })
  }
}
</script>

<style scoped lang="scss">
.context-menu {
  position: absolute;
  .menu-list {
    padding: 0 10px;
    box-shadow: 0 0 2px 2px #f1f1f1;
    background: #fff;
    .menu-item {
      display: flex;
      align-items: center;
      height: 30px;
      padding: 4px 5px;
      gap: 8px;
      text-align: center;
      cursor: pointer;
      &:hover {
        color: #0073e5;
      }
    }
  }
}
</style>
